package com.hframe.http.client;

import com.google.gson.JsonElement;

import java.net.HttpURLConnection;

/**
 * Created by heqian on 12/7/16.
 */
public class JsonParam implements HttpParam {
    protected String contentType = "application/explain;charset=UTF-8";
    protected JsonElement json = null;

    public JsonParam() {
    }

    public JsonParam(JsonElement string) {
        this.json = string;
    }

    @Override
    public void init(HttpURLConnection conn) {
        conn.setRequestProperty("Content-type", contentType);
    }


    @Override
    public long getDataLenght() {
        return json.toString().length();
    }

    @Override
    public String getUrlString() {
        return "";
    }

    @Override
    public boolean read(HttpURLConnection connection, Write write) throws Exception {
        if (null == write)
            return false;

        byte[] data = json.toString().getBytes();
        writeBuffer(write, data);
        return true;
    }

    protected void writeBuffer(Write write, byte[] data) throws Exception {
        for (int index = 0; index < data.length; index += 4096) {
            write.write(data, index, data.length - index > 4096 ? 4096 : data.length - index);
        }
    }
}
